$(document).ready(function () {
    var row = 4;  //行数
    var col = 5;  //列数
    var totimage = 6;  //图片总数量
    var totrow = row + 2;  //横+2
    var totcol = col + 2;  //竖+2
    var ii, jj;
    var jieguo;
    var totalNum = 0;
    var zg = row * col;
    var mapp = new Array(totcol);
    var image = row * col / 2;
    var imagesz = new Array(image);
    var temp1 = null;   //第一个点
    var twopic = new Array({ x: 0, y: 0 }, { x: 0, y: 0 });  //点击的两个点
    var direct = new Array(5);
    var bianhao = 1;
    var nn = 0;  // 构建图片所需变量
    var html = "<table>\n";   //构建图片所需html变量
    var n = 0;
    var ticketObj;
    var usr_sign = untils.getQueryString("usr_sign");
    var usr_nonce = untils.getQueryString("usr_nonce");
    var usr_ts = untils.getQueryString("usr_ts");
    var checkToken = {
        usr_sign: usr_sign,
        usr_nonce: usr_nonce,
        usr_ts: usr_ts
    };
    var usr_info = JSON.parse(untils.getQueryString("wxUserInfo"));
    var activityID = "40298198600716a5016048c9215e36d3";
    var shareTxt = "冬至和老孙的“火眼金睛”有关系？免费旅游名额等你拿！";
    var shareLink = "http://tpn.gzl.com.cn/static/game/WinterSolstice/html/playgame.html";
    var vConsole = new VConsole();
    console.log('usr_sign:', usr_sign);
    console.log('usr_info:', usr_info);

    //方格地图数组初始化
    for (var j = 0; j < totcol; j++) {
        mapp[j] = new Array(totrow);
    }

    var flag = new Array(totcol);
    for (var j = 0; j < totcol; j++) {
        flag[j] = new Array(totrow);
    }

    for (j = 0; j < 5; j++) {
        direct[j] = new Array(3);
    }
    direct[0][0] = 0; direct[0][1] = 1;
    direct[2][0] = 0; direct[2][1] = -1;
    direct[1][0] = 1; direct[1][1] = 0;
    direct[3][0] = -1; direct[3][1] = 0;


    //生成图片数组，名称为1-6
    for (var i = 0; i < image; i++) {
        if (bianhao > totimage) {
            bianhao = Math.ceil(Math.random() * 6);
        }
        imagesz[nn] = bianhao;
        imagesz[nn + 1] = bianhao;
        nn = nn + 2;
        bianhao++;
    }
    imagesz = untils.randomOrder(imagesz);  //随机编排顺序



    for (var c = 0; c < totcol; c++) {
        html += "<tr>\n";
        for (var r = 0; r < totrow; r++) {
            //第一行第一列不放图片
            if (c == 0 || r == 0 || r == (totrow - 1) || c == (totcol - 1)) {
                html += "<td>\n";
                mapp[c][r] = 0;
            } else {
                html += "<td class='td_bg'>"
                mapp[c][r] = imagesz[n];
                n++;
                html += "<img data=" + mapp[c][r] + " src=\"../images/" + mapp[c][r] + ".png\" onclick=\"jiancha(this, " + c + ", " + r + ");\">\n";
            }
            html += "</td>\n";
        }
    }

    document.getElementById("gzl_llk").innerHTML = html;

    jiancha = function (temp2, x, y) {
        console.log('111111');
        if (mapp[x][y] != 0) {
            // var src_data = 1;
            if (temp1 == null) {   //当点击第一个点时
                temp1 = temp2;
                var src_data = temp1.getAttribute('data');
                console.log('temp1:', temp1, src_data);
                // temp1.style.background = "url(../images/" + src_data +"1.png) no-repeat top center";
                // temp1.style.backgroundSize = "100% 100%";
                $(temp1).attr('src', '../images/' + src_data +'1.png');
                twopic[0].x = x;
                twopic[0].y = y;
            } else if (temp2 != temp1) {
                var _src_data = temp1.getAttribute('data');
                // temp1.style.background = "url(../images/" + _src_data +".png) no-repeat top center";
                // temp1.style.backgroundSize = "100% 100%";
                $(temp1).attr('src', '../images/' + _src_data +'.png')
                twopic[1].x = x;
                twopic[1].y = y;
                if (mapp[twopic[0].x][twopic[0].y] == mapp[twopic[1].x][twopic[1].y]) {	  //判断是否是同一张图片
                    // console.log('twopic=', mapp[twopic[0].x][twopic[0].y], mapp[twopic[1].x][twopic[1].y])
                    for (ii = 0; ii < totcol; ii++) {
                        for (jj = 0; jj < totrow; jj++) {
                            flag[ii][jj] = 0;
                        }
                    }
                    // console.log('flag==',flag);
                    flag[twopic[0].x][twopic[0].y] = 1;
                    jieguo = 0;
                    panduan(twopic[0].x, twopic[0].y, 0, -1);

                    if (jieguo == 1) {
                        totalNum++;
                        if (totalNum == 10) {
                            console.log('结束secondtime_nz:', untils.secondtime_nz)
                            if (untils.secondtime_nz > 0) {   
                                clearInterval(untils.counttimer);                             
                                
                                untils.gamesubmit(activityID, 'weixin', ticketObj, JSON.stringify(totalNum), function (gamesubmitdata) {
                                    console.log('submitresult-data', gamesubmitdata);     
                                    $('.finish_box').show();
                                    setTimeout(() => {
                                        $('.flower').each(function () {
                                            var oddnum = $(this).index() % 2 ? '+' : '-';
                                            $(this).animate({
                                                "top": '-' + (Math.random() * 20 + 35) + '%',
                                                "left": oddnum + Math.random() * 200 + '%',
                                                'opacity': '0'
                                            }, 1200)
                                        })
                                    }, 500);                              
                                })
                            }else{
                                $('.remain_num').text(81 - totalNum);
                                $('.fail_box').show();
                            }
                            return false;
                        }
                        if(totalNum % 9 == 0){
                            untils.shovelSnow(2,totalNum/9);
                        }
                        console.log('totalNum: ', totalNum);
                        untils.scoreChangePic(totalNum, $('.score_num'))
                        var random1_img = Math.ceil(Math.random() * 6);
                        var random2_img = Math.ceil(Math.random() * 6);
                        var temp1_p = temp1.parentNode;
                        var temp2_p = temp2.parentNode;
                        temp1.parentNode.removeChild(temp1);
                        temp2.parentNode.removeChild(temp2);
                        // console.log('temp1_p=',temp1_p);
                        mapp[twopic[0].x][twopic[0].y] = random1_img;
                        mapp[twopic[1].x][twopic[1].y] = random2_img;
                        setTimeout(function(){
                            temp1_p.innerHTML = "<img data=" + random1_img +" src=\"../images/" + random1_img + ".png\" onclick=\"jiancha(this, " + twopic[0].x + ", " + twopic[0].y + ")\">\n";
                            temp2_p.innerHTML = "<img data=" + random1_img +" src=\"../images/" + random2_img + ".png\" onclick=\"jiancha(this, " + twopic[1].x + ", " + twopic[1].y + ")\">\n";
                        },150)

                        zg = zg - 2;
                        if (zg == 0) {

                        }
                    }
                }
                temp1 = null;
            }
        }
    }

    //接下来用到的是DFS(深度优先搜索)对两个点进行判断能不能消除
    function panduan(nowx, nowy, tj, father) {
        var i;
        if (tj > 2) return;
        if (nowx == twopic[1].x && nowy == twopic[1].y && tj <= 2) {
            jieguo = 1;
            return;
        }
        for (i = 0; i < 4; i++) {  //这里为什么至少要循环4次呢？
            var xxx = nowx + direct[i][0];   //这里的direct[i]的作用是什么呢？   -----初步判断 是想通过  +direct的值 是否是最外围
            var yyy = nowy + direct[i][1];
            if (xxx >= 0 && xxx < totcol && yyy >= 0 && yyy < totrow) {
                //mapp[xxx][yyy]==0  表示最外围一栏空的那栏，即nowx是看得见的最后一栏
                if ((flag[xxx][yyy] == 0 && mapp[xxx][yyy] == 0) || (xxx == twopic[1].x && yyy == twopic[1].y)) {
                    if (i % 2 == father % 2 || father == -1) {
                        flag[xxx][yyy] = 1;
                        panduan(xxx, yyy, tj, i);
                        flag[xxx][yyy] = 0;
                    } else {
                        flag[xxx][yyy] = 1;
                        panduan(xxx, yyy, tj + 1, i);
                        flag[xxx][yyy] = 0;
                    }
                }
            }
        }
    }

    //花瓣
    $('.flower').each(function(){
        // console.log('$(this).index()=', $(this).index())
        var _left = Math.ceil(Math.random() * 40) + 20;
        var _top = Math.ceil(Math.random() * 60) + 10;
        $(this).css({
            'left': _left+'%',
            'top': _top + '%'
        })       
    })

    // 获取游戏机会
    // 游戏管理1  ff808081604f1860016053bd452f0982   40298198600716a5016048c9215e36d3
    // 游戏管理2  ff808081604f186001605334ec98095c
    untils.getTicket(activityID, 'weixin', function(data){
        if (data.desc == "不能参与此游戏") {
            console.log('机会用完啦');
            // noChance.style.display = "block";
            $('.no_chance_box').show();
        } else {
            ticketObj = data.responseObject;
            console.log('ticketObj',ticketObj);
        }
    })


    //分享
    untils.weChatConfig(shareLink, shareTxt, function () {
        untils.sharegame(activityID, 'weixin', function(sharedata){
            console.log("分享成功--before", sharedata);
            if (sharedata.desc == "游戏分享成功") {
                window.location.href = "http://tpn.gzl.com.cn/static/game/WinterSolstice/html/playgame.html";
            } else {
                alert("分享出错");
            }
        })
    })

    //是否关注
    if (!usr_info.subscribe) {
        // alert('usr_sign:', usr_sign)
        $('.follow_qr_box').show();
        return false;
    }

    //点击开始游戏
    $('.start').click(function(){
        var three_s_timer = null,
            s_count_time = 2,
            b_position_x = 100;
        $(this).parent('.start_bg').hide('fast',function(){
            three_s_timer = setInterval(function(){
                console.log(s_count_time, b_position_x);
                if (s_count_time <= 0) {  //3s倒计时结束，游戏开始
                    clearInterval(three_s_timer);
                    untils.playgame(activityID, 'weixin', ticketObj, function (playdata){
                        if (playdata.desc == "游戏开始成功"){
                            $('.countdown_three').hide();
                            //90s倒计时开始
                            untils.countclock($('.countclock'),function(){
                                console.log('secondtime_nz:', untils.secondtime_nz);
                                if (totalNum >= 10) {
                                    untils.gamesubmit(activityID, 'weixin', ticketObj, JSON.stringify(totalNum), function (gamesubmitdata) {
                                        console.log('submitresult-data', gamesubmitdata);
                                        setTimeout(() => {
                                            $('.flower').each(function () {
                                                var oddnum = $(this).index() % 2 ? '+' : '-';
                                                $(this).animate({
                                                    "top": '-' + (Math.random() * 20 + 35) + '%',
                                                    "left": oddnum + Math.random() * 200 + '%',
                                                    'opacity': '0'
                                                }, 1200)
                                            })
                                        }, 500);
                                    })
                                }else{
                                    $('.remain_num').text(81-totalNum);
                                    $('.fail_box').show();
                                }
                               
                            });
                            untils.standOcation(3);   //猴哥开始动
                            clearInterval(three_s_timer);
                        }else{
                            console.log("paly 游戏开始时网络出错:", playdata.desc)
                            // alert("网络出错哦，请重新请求吧！");
                        }
                    })
                }else{
                    s_count_time--;
                    b_position_x = b_position_x - 55;
                }
                $('.three_second').css({
                    "background-position": b_position_x+"% 0%"
                })
            },1000)
        });
    })


    //一键分享
    $('.share_btn').click(function(){
        $('.fail_bg').hide();
        $('.shareTip').show();
    })


    // 点击抽奖
    $('.lottery').click(function(){
        var check_toke = JSON.stringify(checkToken);
        window.location = "http://tpn.gzl.com.cn/static/game/WinterSolstice/html/turnplate.html?checkToken=" + encodeURIComponent(check_toke) + "&ticketObj=" + JSON.stringify(ticketObj);
    })

})








